package com.junyu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.junyu.common.ResultCodeEnum;
import com.junyu.exception.LoginException;
import com.junyu.mapper.RegisterMapper;
import com.junyu.pojo.entity.User;
import com.junyu.service.RegisterService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

/**
 * 注册接口实现类
 */
@Service
public class RegisterServiceImpl extends ServiceImpl<RegisterMapper, User> implements RegisterService {
    @Autowired
    private RegisterMapper registerMapper;


    /**
     * 注册用户
     * @param user 用户对象
     */
    @Override
    public void register(User user) {
        //注册时必须绑定邮箱
        if (StringUtils.isEmpty(user.getEmail())) {
           throw new LoginException(ResultCodeEnum.EMAIL_IS_NULL);
        }
        //密码必须包含大小写字母和数字，长度不小于8，至少包含数字、小写、大写中的两个或两个以上，且必须以字母开头
        if (user.getPassword() == null || !user.getPassword().matches("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).{8,}$")) {
            throw new LoginException(ResultCodeEnum.PASSWORD_FORMAT_ERROR);
        }
        if(user.getUserName() == null || !user.getUserName().matches("^[a-zA-Z][a-zA-Z0-9_-]{5,}$")){
            throw new LoginException(ResultCodeEnum.USER_NAME_FORMAT_ERROR);
        }
        //邮箱格式校验
        if (!user.getEmail().matches("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$")) {
            throw new LoginException(ResultCodeEnum.EMAIL_FORMAT_ERROR);
        }
        //校验用户名和邮箱的唯一性
        User dbUser1 = this.getOne(new LambdaQueryWrapper<User>().eq(User::getEmail, user.getEmail()));
        User dbUser2 = this.getOne(new LambdaQueryWrapper<User>().eq(User::getUserName, user.getUserName()));
        if (dbUser1 != null || dbUser2 != null) {
            throw new LoginException(ResultCodeEnum.USER_NAME_EMAIL_NOT_ONLY);
        }
        //将密码加密
        String iptPassword = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(iptPassword);
        //插入注册用户的信息
        this.registerMapper.insert(user);
    }
}
